package tomsung.cloud.agdc.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import tomsung.cloud.agdc.bean.User;
import tomsung.cloud.agdc.security.SecurityUtil;
import tomsung.cloud.agdc.service.UserService;

@Controller
@RequestMapping("/sec")
public class SecController {


	@Autowired
	private UserService userService;


	@ResponseBody
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	protected Map<String, Object> login(final HttpServletRequest request, @RequestBody User user) {

		Map<String, Object> map = new HashMap<String, Object>();
		User userTmp = userService.login(user.getUsername());
		if (userTmp != null && user != null && user.getPassword().equals(userTmp.getPassword())) {
			SecurityUtil.login(request, userTmp);
			map.put("REALNAME", userTmp.getRealusername());
			map.put("TEL", userTmp.getTel());
			map.put("USERURL", userTmp.getUserurl());
			map.put("USERID", userTmp.getUserid());
			map.put("R", true);
		} else {
			map.put("R", false);
			map.put("ERR_MSG", "用户名或者密码错误！");
		}
		return map;
	}

	@ResponseBody
	@RequestMapping(value = "/logout", method = RequestMethod.POST)
	protected Map<String, Object> logout(final HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		SecurityUtil.logout(request);
		map.put("R", true);
		return map;
	}

	@RequestMapping(value = "/index", method = RequestMethod.GET)
	protected ModelAndView index(final ModelAndView mav) {
		mav.setViewName("/sec/login");
		return mav;
	}

	
	@ResponseBody
	@RequestMapping(value = "/queryloginuser", method = RequestMethod.POST)
	protected User queryLoginUser(final HttpServletRequest request) {

		User user = SecurityUtil.getLoginUser(request);
		User userCopy = new User();
		userCopy.setUserid(user.getUserid());
		userCopy.setUsername(user.getUsername());
		userCopy.setAddress(user.getAddress());
		userCopy.setCreattime(user.getCreattime());
		userCopy.setEmail(user.getEmail());
		userCopy.setGroupid(user.getGroupid());
		userCopy.setRealusername(user.getRealusername());
		userCopy.setUserurl(user.getUserurl());
		userCopy.setTel(user.getTel());
		userCopy.setValidTime(user.getValidTime());
		userCopy.setVerCode(user.getVerCode());
		return userCopy;
	}

	class GreenhouseTmp {
		public Integer greenhouseId = -1;
		public String greenhouseName = "";
		public String greenhouseAddress = "";
	}
}
